package com.inight.ojcodesandbox.docker;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.inight.ojcodesandbox.CodeSandbox;
import com.inight.ojcodesandbox.model.ExecuteCodeRequest;
import com.inight.ojcodesandbox.model.ExecuteCodeResponse;
import com.inight.ojcodesandbox.model.ExecuteMessage;
import com.inight.ojcodesandbox.model.JudgeInfo;
import com.inight.ojcodesandbox.utils.ProcessUtils;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * java 原生的实现方式
 */
public class DockerCodeSandboxOld implements CodeSandbox {


    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long TIME_OUT = 5000L;

    // 代码中有这些黑名单中的词 直接禁掉
    private static final List<String> blackList = Arrays.asList("Files", "exec");

    private static final WordTree WORD_TREE;
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";
    // 到 path 中的上级目录, 不包括 class 本身
    private static final String SECURITY_MANAGER_PATH = "D:\\Java\\own\\inight-oj\\oj-code-sandbox\\src\\main\\resources\\security";
    private static final boolean FIRST_INIT = true;

    static {
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }

    public static void main(String[] args) {
        DockerCodeSandboxOld dockerCodeSandbox = new DockerCodeSandboxOld();
        ExecuteCodeRequest request = new ExecuteCodeRequest();
        request.setInputList(Arrays.asList("1 2", "1 3"));
        // 从文件中读取内容
        String code = ResourceUtil.readUtf8Str("tmpCode/testCode/simpleComputeArgs/Main.java");
        request.setCode(code);
        request.setLanguage("java");
        ExecuteCodeResponse response = dockerCodeSandbox.executeCode(request);
        System.out.println(response);
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        // 设置自己写的安全管理器. 这个应该设置到 命令行中
        // System.setSecurityManager(new DefaultSecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 保存为文件之前, 先校验用户代码有没有危险代码, 比如操作文件和读文件
        // 利用 hutool 的字典树
//        WordTree wordTree = new WordTree();
//        wordTree.addWords(blackList);
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if(foundWord != null) {
            // 说明有危险代码
            System.out.println("危险代码: " + foundWord.getFoundWord());
            return null;
        }

        // 1. 将用户提交的代码保存为文件
        // 获取用户工作文件路径
        String userDir = System.getProperty("user.dir");
        // D:\Java\own\inight-oj\oj-code-sandbox
        System.out.println("user.dir = " + userDir);
        //  File.separator 区分不太系统的分隔符：\\ or /
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        System.out.println(globalCodePathName);
        // 判断全局路径是否存在, 用到 hutool文件工具类, 比java 原生的读取文件 api要好用
        if(!FileUtil.exist(globalCodePathName)) {
            // 不存在, 就创建目录
            File mkdir = FileUtil.mkdir(globalCodePathName);
            // 创建之后的目录: D:\Java\own\inight-oj\oj-code-sandbox\tmpCode
            System.out.println("创建之后的目录: " + mkdir.getPath());
            // java 原生创建文件方式
//            File file = new File(globalCodePathName);
//            file.mkdir();
        }

        // todo 需要重新写一遍
        // 存在，则保存用户提交代码
        // 把用户的代码隔离存放，这个是目录
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        // 实际存放文件的目录
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME  ;
        // 写入文件. 利用 hutool 工具类
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        // 2、编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            // 得到一个进程 Process
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            // 等待 Process 程序执行完，获取错误码
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            return getErrorResponse(e);
            // throw new RuntimeException(e);
        }

        // 3. 创建容器, 上传编译文件 (这一步和之前的不一样)
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";
        // 第一次初始化, 需要拉取镜像
        if(FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("拉取镜像: " + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像失败: " + e.getMessage());
                throw new RuntimeException(e);
            }
        }
        System.out.println("拉取镜像成功");

        // 创建一个可交互的容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        // 限制内存
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L); // 表示不和硬盘进行交换, 也就是不把内存中的信息写到硬盘中
        // 设置CPU
        hostConfig.withCpuCount(1L);
        // todo 设置一些安全限制, 比如读取文件啥的
        hostConfig.withSecurityOpts(Arrays.asList("seccomp=安全管理配置字符串"));
        // 设置容器挂载目录
        // 最好设置是文件的目录. 就是挂载文件. 挂载的文件不要放在根目录
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true) // 禁掉网络, 代码不能操作网络
                .withReadonlyRootfs(true) // todo 限制用户不能向跟目录写文件
                .withAttachStderr(true) // 开启输入输出
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true) // 开启一个交互终端
                .exec();
        String containerId = createContainerResponse.getId();
        System.out.println("创建容器id：" + containerId);

        // 启动容器, 执行命令
        // ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd();
        // 4、执行命令 docker exec containtId java -cp /app Main 1 2
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            // 判断是否超时. todo
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            // 变量捕获, alt + enter 自动解决
            final long[] maxMemory = {0L};

            // 获取占用的内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        // todo 这里设置超时时间, 过了这个时间就会往下走, 不会继续等.  但是会有无论超时与否, 都会往下执行, 无法判断是否超时
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        // 4、封装结果，跟原生实现方式完全一致
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存占用，非常麻烦，此处不做实现
//        judgeInfo.setMemory();

        executeCodeResponse.setJudgeInfo(judgeInfo);

//        5. 文件清理
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;

    }

    /**
     * 错误信息处理, 提升程序健全性
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Exception e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //  2 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        
        return executeCodeResponse;
    }
    
    
//    public static void main(String[] args) {
//        String property = System.getProperty("user.dir");
//        System.out.println(property);
//    }

}
